package com.finance.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finance.entity.SalesRawMaterial;
import com.finance.mapper.SalesRawMaterialMapper;
import com.finance.service.SalesRawMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * C09
 * 销售消耗原材料数据    Service实现类
 */
@Slf4j
@Service
public class SalesRawMaterialServiceImpl extends ServiceImpl<SalesRawMaterialMapper, SalesRawMaterial> implements SalesRawMaterialService {

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int processOrders(List<Map<String, String>> records, String searchDate, boolean forceUpdate, String cinemaId) {
        if (records == null || records.isEmpty()) {
            log.warn("No records to process for C09 data");
            return 0;
        }

        // 如果不是强制更新，先检查数据是否存在
        if (!forceUpdate) {
            long count = lambdaQuery()
                .eq(SalesRawMaterial::getSearchDate, searchDate)
                .eq(SalesRawMaterial::getCinemaId, cinemaId)
                .count();
            if (count > 0) {
                log.info("C09数据已存在，searchDate: {}, cinemaId: {}, 跳过处理", searchDate, cinemaId);
                return 0;
            }
        } else {
            // 如果是强制更新，先删除指定日期和影院ID的数据
            lambdaUpdate()
                .eq(SalesRawMaterial::getSearchDate, searchDate)
                .eq(SalesRawMaterial::getCinemaId, cinemaId)
                .remove();
        }

        List<SalesRawMaterial> materialList = new ArrayList<>();
        for (Map<String, String> record : records) {
            try {
                //影院名称,影院编码,销售时间,售订单号,退订单号,取货状态,销售类型,销售地点,大类,大类编码,货品编码
                SalesRawMaterial material = new SalesRawMaterial();
                if (StringUtils.hasText(record.get("影院名称"))) {
                    material.setCinemaName(record.get("影院名称"));
                }
                if (StringUtils.hasText(record.get("影院编码"))) {
                    material.setCinemaCode(record.get("影院编码"));
                }
                material.setCinemaId(cinemaId);
                // 处理销售时间
                String saleTimeStr = record.get("销售时间");
                if (StringUtils.hasText(saleTimeStr)) {
                    try {
                        material.setSaleTime(LocalDateTime.parse(saleTimeStr, DATE_TIME_FORMATTER));
                    } catch (Exception e) {
                        log.warn("Invalid sale time format: {}", saleTimeStr);
                    }
                }
                if (StringUtils.hasText(record.get("售订单号"))) {
                    material.setSaleOrderNo(record.get("售订单号"));
                }
                if (StringUtils.hasText(record.get("退订单号"))) {
                    material.setRefundOrderNo(record.get("退订单号"));
                }
                if (StringUtils.hasText(record.get("取货状态"))) {
                    material.setPickupStatus(record.get("取货状态"));
                }
                if (StringUtils.hasText(record.get("销售类型"))) {
                    material.setSaleType(record.get("销售类型"));
                }
                if (StringUtils.hasText(record.get("销售地点"))) {
                    material.setSaleLocation(record.get("销售地点"));
                }
                if (StringUtils.hasText(record.get("大类"))) {
                    material.setCategory(record.get("大类"));
                }
                if (StringUtils.hasText(record.get("大类编码"))) {
                    material.setCategoryCode(record.get("大类编码"));
                }
                if (StringUtils.hasText(record.get("货品编码"))) {
                    material.setGoodsCode(record.get("货品编码"));
                }
                // 货品名称,货品数量,材料编码,材料名称,材料数量,速记代码,单位,包装条形码,取货时间
                if (StringUtils.hasText(record.get("货品名称"))) {
                    material.setGoodsName(record.get("货品名称"));
                }
                // 处理货品数量
                String goodsQuantityStr = record.get("货品数量");
                if (StringUtils.hasText(goodsQuantityStr)) {
                    try {
                        material.setGoodsQuantity(new BigDecimal(goodsQuantityStr));
                    } catch (Exception e) {
                        log.warn("Invalid goods quantity format: {}", goodsQuantityStr);
                    }
                }
                if (StringUtils.hasText(record.get("材料编码"))) {
                    material.setMaterialCode(record.get("材料编码"));
                }
                if (StringUtils.hasText(record.get("材料名称"))) {
                    material.setMaterialName(record.get("材料名称"));
                }
                // 处理材料数量
                String materialQuantityStr = record.get("材料数量");
                if (StringUtils.hasText(materialQuantityStr)) {
                    try {
                        material.setMaterialQuantity(new BigDecimal(materialQuantityStr));
                    } catch (Exception e) {
                        log.warn("Invalid material quantity format: {}", materialQuantityStr);
                    }
                }
                if (StringUtils.hasText(record.get("速记代码"))) {
                    material.setShorthandCode(record.get("速记代码"));
                }
                if (StringUtils.hasText(record.get("单位"))) {
                    material.setUnit(record.get("单位"));
                }
                if (StringUtils.hasText(record.get("包装条形码"))) {
                    material.setPackageBarcode(record.get("包装条形码"));
                }
                // 处理取货时间
                String pickupTimeStr = record.get("取货时间");
                if (StringUtils.hasText(pickupTimeStr)) {
                    try {
                        material.setPickupTime(LocalDateTime.parse(pickupTimeStr, DATE_TIME_FORMATTER));
                    } catch (Exception e) {
                        log.warn("Invalid pickup time format: {}", pickupTimeStr);
                    }
                }
                material.setSearchDate(searchDate);
                
                materialList.add(material);
            } catch (Exception e) {
                log.error("Error processing C09 record: {}", record, e);
                throw new RuntimeException("Failed to process C09 record", e);
            }
        }

        try {
            saveBatch(materialList);
            return materialList.size();
        } catch (Exception e) {
            log.error("Error saving C09 data batch", e);
            throw new RuntimeException("Failed to save C09 data batch", e);
        }
    }
} 